package com.example.booksmanagementsystem.mapper;

import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.type.JdbcType;
import java.util.List;
import com.example.booksmanagementsystem.entity.Book;
@Mapper      //数据库服务接口
@Service    //是普通服务类
@Repository //是数据库仓库类
public interface BookMapper {

    // 获取所有图书
    @Select("SELECT * FROM book")
    @Results({
            @Result(property = "id", column = "id", jdbcType = JdbcType.INTEGER),
            @Result(property = "name", column = "name", jdbcType = JdbcType.VARCHAR),
            @Result(property = "type", column = "type", jdbcType = JdbcType.VARCHAR),
            @Result(property = "author", column = "author", jdbcType = JdbcType.VARCHAR),
            @Result(property = "price", column = "price", jdbcType = JdbcType.FLOAT),
            @Result(property = "pic", column = "pic", jdbcType = JdbcType.VARCHAR),
            @Result(property = "createDate", column = "create_date", jdbcType = JdbcType.DATE)
    })
    List<Book> getAllBooks();

    //获取图书总数
    @Select("select count(*) from book")
    int getNums();

    // 分页获取所有图书
    @Select("SELECT * FROM book LIMIT #{start}, #{limit}")
    List<Book> getBooksByPage(@Param("start") int start, @Param("limit") int limit);

    // 按编号获取图书
    @Select("SELECT * FROM book WHERE id = #{id}")
    Book getBookById(@Param("id") int id);

    // 按名字获取图书
    @Select("SELECT * FROM book WHERE name LIKE CONCAT('%', #{name}, '%')")
    List<Book> getBooksByName(@Param("name") String name);

    // 增加图书
    @Insert("INSERT INTO book (name, type, author, price, pic, create_date) VALUES(#{name}, #{type}, #{author}, #{price}, #{pic}, #{createDate})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void addBook(Book book);

    // 删除图书
    @Delete("DELETE FROM book WHERE id = #{id}")
    void deleteBook(@Param("id") int id);

    // 修改图书
    @Update("UPDATE book SET name = #{name}, type = #{type}, author = #{author}, price = #{price}, pic = #{pic}, create_date = #{createDate} WHERE id = #{id}")
    void updateBook(Book book);
}
